package ch5.ex8;

import static ch5.print.Print.*;

class Connection{
    
    private static int count = 0;
    private int i = 0;
    
    private Connection() {
        println("Connection()");
    }
    
    static Connection makeConnection() {
        count++;
        return new Connection();
    }
    
    public static int howMany() {
        return count;
    }
    
    public String toString() {
        return("Connection " + count);
    }
}

public class ConnectionManager {
    
    static int howManyLeft = 3;
    
    static Connection[] ca = new Connection[3];
    
    {
        for (Connection x : ca) {
            x = Connection.makeConnection();
        }
    }
    
    public static Connection getConnection() {
        if(howManyLeft >0)
            return ca[--howManyLeft];
        else {
            println("No more Connection");
            return null;
        }
    }
    
    public static void main(String... args) {
        ConnectionManager cm = new ConnectionManager();
        println(cm.howManyLeft);
        cm.getConnection();
        println(howManyLeft);
        cm.getConnection();
        println(howManyLeft);
        cm.getConnection();
        println(cm.getConnection());
        println(howManyLeft);
    }
}
